/**
 * Created by bootdo.
 */
import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

axios.defaults.withCredentials = true;
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
//  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';//配置请求头
import {
    bus
} from '../bus.js'

let time = null;
let code = null;
axios.interceptors.request.use(
    config => {
        //请求头需要带token
        let loginUserOnlyCode = null;
        let obj = {};
        let url = window.location.href;
        if (url.indexOf("?") != -1) {
            var str = url.split("?")[1];
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                obj[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
            loginUserOnlyCode = obj['loginUserOnlyCode']
        }

        if (config.params) {
            config.params.loginUserOnlyCode = loginUserOnlyCode;
        } else {
            config.params = {
                loginUserOnlyCode: loginUserOnlyCode
            }
        }
        if (window.localStorage.getItem('access-token')) {
            config.headers.Authorization = window.localStorage.getItem('access-token');
            let webAccessUser = JSON.parse(localStorage.getItem('web-access-user'));

            config.headers.Authorization = window.localStorage.getItem('access-token');

        }
        NProgress.start()
        return config
    },
    error => {
        return Promise.reject(error)
    }
);
// 添加一个响应拦截器
axios.interceptors.response.use(function(response) {
    // console.log(response)
    if (response.data && response.data.code) {
        if (parseInt(response.data.code) === 401) {
            //未登录
            bus.$emit('goto', '/login')
        } else if (parseInt(response.data.code) === 402) {
            bus.$emit('goto', '/webLogin')
        }
    }
    NProgress.done()
    return response;
}, function(error) {
    // Do something with response error
    return Promise.reject(error);
});

//基地址
let base = process.env.API_ROOT


//通用方法
export const POST = (url, params) => {
    return axios.post(`${base}${url}`, params).then(res => res.data)
}

//通用方法
export const POST2 = (url, params) => {
    // return axios.post(`${base}${url}`,qs.stringify(data)).then(res => res.data)
    return new Promise((resolve, reject) => {
        axios.post(`${base}${url}`, params,
            // 将axios 对象obj数据的post请求转化为formdata格式
            {
                transformRequest: [function (data) {
                    let ret = ''
                    for (let it in data) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    return ret
                }], headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }
        ).then(res => {
            resolve(res.data);
        }).catch((error) => {
            reject(error)
        })
    })
}
export const GET = (url, params) => {
    return axios.get(`${base}${url}`, {
        params: params
    }).then(res => res.data)
}

export const PUT = (url, params) => {
    return axios.put(`${base}${url}`, params).then(res => res.data)
}

export const DELETE = (url, params) => {
    return axios.delete(`${base}${url}`, {
        params: params
    }).then(res => res.data)
}

export const PATCH = (url, params) => {
    return axios.patch(`${base}${url}`, params).then(res => res.data)
}
export const FILEUPLOAD = (url) => {
        return `${base}${url}`;
    }
    //不带进度条的
export const uploadFile2 = (url, params) => {
        return axios.post(`${base}${url}`, params, { headers: { 'Content-Type': 'Multipart/form-data' } }).then(res => res.data)
    }
    //带进度条的
export const uploadFile3 = (url, params, rogress) => {
    return axios.post(`${base}${url}`, params, {
        headers: { 'Content-Type': 'Multipart/form-data' },
        onUploadProgress: rogress.onUploadProgress,
        timeout: 1000 * 60 * 10
    }).then(res => res.data)
}
export const downloadFile = (url, params) => {
        window.location.href = `${base}${url}?list=${params}`;
    }
    // 图片验证码
export const IMGCODE = (url) => {
    return `${base}${url}`;
}